<?php
namespace Emos\Editor;

use Emos\Common;
use Emos\Field;

class Form {   
    var $entity;
    
    var $elementSet;
    
    /** Form template */
    protected $template = null;

    protected $hiddenFields = array();

    public function __construct() {
         $this->elementSet = new Field\ItemSet();
    }    
    
    public function setHiddenFields(array $hiddenFields) {
        $this->hiddenFields = $hiddenFields;
    }
    
    public function init() {
        $controls = $this->elementSet->getControls();
        foreach ($controls as $name=>$control) {
            $control->form = $this;
            $control->initName($name, "field_{$name}");
        }
    }    
    
    public function setValuesFromRecord($record) {            
        foreach ($this->elementSet->getControls() as $control) {
            $control->setValueFromRecord($record);
        }        
    }
    
    public function getHtml() {        
        $template = $this->elementSet->getTemplate();
        $controls = $this->elementSet->getControls();
        
        $vals = array();
        foreach($controls as $name=>$control) {            
            $vals['{'.$name.'}'] = $control->getHtml();
        }        
        
        $hf = '';
        foreach ($this->hiddenFields as $name=>$value) {
            //$hf .= " {$name}:<input type='_hidden' name='$name' value='".Common::plain($value)."'>";                                    
            $hf .= "<input type='hidden' name='$name' value='".Common::plain($value)."'>";                                    
        }        
        
        return $hf.strtr($template, $vals);
    }    
}
